﻿// ===============================================================================
// DotNet.Platform 开发框架 2016 版权所有
// ===============================================================================

using System;
using System.Diagnostics;
using System.Web.Mvc;
using DotNet.Helper;

namespace DotNet.Mvc
{
    public class TimingActionAttribute : ActionFilterAttribute
    {
        /// <summary>
        /// 项目名称
        /// </summary>
        public string Project { get; set; }
         
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            GetTimer(filterContext, "action").Start();
            base.OnActionExecuting(filterContext);
        }
        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            GetTimer(filterContext, "action").Stop();
            base.OnActionExecuted(filterContext);
        }
        public override void OnResultExecuted(ResultExecutedContext filterContext)
        {
            var renderTimer = GetTimer(filterContext, "render");
            renderTimer.Stop();
            var actionTimer = GetTimer(filterContext, "action");
            //if (actionTimer.ElapsedMilliseconds >= 100 || renderTimer.ElapsedMilliseconds >= 100)
            {
                var acc = filterContext.RouteData.Values;
                LogHelper.Message($"{Project} {acc["controller"]}/{acc["action"]},执行:{actionTimer.ElapsedMilliseconds}ms,渲染:{renderTimer.ElapsedMilliseconds}ms");
            }
            base.OnResultExecuted(filterContext);
        }
        public override void OnResultExecuting(ResultExecutingContext filterContext)
        {
            GetTimer(filterContext, "render").Start();
            base.OnResultExecuting(filterContext);
        }
        private Stopwatch GetTimer(ControllerContext context, string name)
        {
            string key = "__timer__" + name;
            if (context.HttpContext.Items.Contains(key))
            {
                return (Stopwatch)context.HttpContext.Items[key];
            }

            var result = new Stopwatch();
            context.HttpContext.Items[key] = result;
            return result;
        }
    }
}